package com.jiawa.train.business.mq;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.jiawa.train.business.domain.ConfirmOrder;
import com.jiawa.train.business.domain.Req.ConfirmOrderDoReq;
import com.jiawa.train.business.service.ConfirmOrderService;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RocketMQMessageListener(consumerGroup = "default",topic = "confirmOrder")
public  class ConfirmOrderConsumer implements RocketMQListener<MessageExt> {

    /*@Autowired
    private ConfirmOrderService confirmOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        System.out.println("RockerMQ 收到的消息为：" + new String(body));
        ConfirmOrderDoReq confirmOrder = JSON.parseObject(new String(body), ConfirmOrderDoReq.class);
        try {
            confirmOrderService.doConfirm(confirmOrder);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/


    @Autowired
    private ConfirmOrderService confirmOrderService;
    @Autowired
    private RedissonClient redissonClient; // 注入Redisson客户端

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        ConfirmOrderDoReq confirmOrder = JSON.parseObject(new String(body), ConfirmOrderDoReq.class);

        // 生成锁的key: 日期+车次
        String key = DateUtil.formatDate(confirmOrder.getDate()) + "-" + confirmOrder.getTrainCode();
        RLock lock = redissonClient.getLock(key);

        try {
            // 尝试获取分布式锁
            if (lock.tryLock(0, 30, TimeUnit.SECONDS)) { // 设置锁超时时间防止死锁
                System.out.println("成功获取分布式锁, 处理订单: " + confirmOrder);
                MDC.put("LOG_ID",confirmOrder.getLogId());
                confirmOrderService.processConfirmOrder(confirmOrder); // 调用无锁的业务方法
            } else {
                System.out.println("未获取到锁, 订单处理失败: " + confirmOrder);
                // 可选: 重试或记录失败日志
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("锁获取中断", e);
        } catch (Exception e) {
            throw new RuntimeException("订单处理异常", e);
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                lock.unlock(); // 确保释放锁
            }
        }
    }
}
